package com.itheima.reggie.controller;

import com.itheima.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.UUID;

/**
 * @author Administrator
 * @date 2023/5/19 8:13
 */
@RestController
@RequestMapping("/common")
@Slf4j
public class CommonController {

    @Value("${reggie.path}")
    private String path;

    /**
     * 上传文件
     *
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public R<String> upload(MultipartFile file) {
        log.info(file.toString());
        //获取文件名字
        String originalFilename = file.getOriginalFilename();
        //截取后缀
        String substring = originalFilename.substring(originalFilename.lastIndexOf("."));
        //使用uuid重新生成名字,防止名字重复
        originalFilename = UUID.randomUUID().toString() + substring;
        //创建目录
        File dir = new File(path);
        if(!dir.exists()){
            dir.mkdirs();
        }
        try {
            file.transferTo(new File(path + originalFilename));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return R.success(originalFilename);
    }
    /**
     * 下载文件
     */
    @GetMapping("/download")
    public void download(String name, HttpServletResponse response){
        try {
            //读取图片
            FileInputStream fileInputStream=new FileInputStream(new File(path+name));
            //上传图片
            ServletOutputStream outputStream = response.getOutputStream();
            //设置上传格式
            response.setContentType("image/jpeg");
            int len=0;
            byte[] bytes=new byte[1024];
            //上传图片的循环
            while ((len=fileInputStream.read(bytes))!=-1){
                outputStream.write(bytes,0,len);
                outputStream.flush();
            }
            fileInputStream.close();
            outputStream.close();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
